﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using RonYee.Service;

namespace RonYee.Controllers
{
    public class NewsController : Controller
    {
        //
        // GET: /News/
        RongeDb db = new RongeDb();

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {
            RonYee.Models.MvcPage Model = new MvcPage();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<News> datesource = GetDataSource();//要分页的数据源
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<News> GetDataSource()
        {
            var news = from b in db.Newss
                          orderby b.AddTime ascending
                          select b;
            List<News> model = new List<News>();
            foreach (var item in news)
            {
                model.Add(item);
            }
            return model;
        }

        public ActionResult PageIndex(RonYee.Models.MvcPage Model)
        {

            //分页数据源。自己写逻辑获取。


            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<News> datesource = GetDataSource();//要分页的数据源
            Model.NewsList = datesource.Where(r => r.NewsId >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("Index", Model);
            }
            //return View(Model);
        }




        public ActionResult List()
        {
            var news = from n in db.Newss select n;
            return View(news.ToList());
        }

        [HttpPost]
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            string cont = Request.Form["s_cont"];
            DateTime start, end;
            start=Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-1-1");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }
            //1111
            if (title != "" && cont != "" && start != null && end != null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.Contents.Contains(cont) && n.AddTime>=start && n.AddTime<=end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1110
            else if (title != "" && cont != "" && start != null && end == null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.Contents.Contains(cont) && n.AddTime >= start
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1101
            else if (title != "" && cont != "" && start == null && end != null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.Contents.Contains(cont) && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1011
            else if (title != "" && cont == "" && start != null && end != null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.AddTime >= start && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0111
            else if (title == "" && cont != "" && start != null && end != null)
            {
                var news = from n in db.Newss
                           where n.Contents.Contains(cont) && n.AddTime >= start && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0011
            else if (title == "" && cont == "" && start != null && end != null)
            {
                var news = from n in db.Newss
                           where n.AddTime >= start && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1100
            else if (title != "" && cont != "" && start == null && end == null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.Contents.Contains(cont)
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1010
            else if (title != "" && cont == "" && start != null && end == null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0101
            else if (title == "" && cont != "" && start == null && end != null)
            {
                var news = from n in db.Newss
                           where n.Contents.Contains(cont) && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0110
            else if (title == "" && cont != "" && start != null && end == null)
            {
                var news = from n in db.Newss
                           where n.Contents.Contains(cont) && n.AddTime >= start
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1001
            else if (title != "" && cont == "" && start == null && end != null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title) && n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //1000
            else if (title != "" && cont == "" && start == null && end == null)
            {
                var news = from n in db.Newss
                           where n.NewsTitle.Contains(title)
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0100
            else if (title == "" && cont != "" && start == null && end == null)
            {
                var news = from n in db.Newss
                           where n.Contents.Contains(cont)
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0010
            else if (title == "" && cont == "" && start != null && end == null)
            {
                var news = from n in db.Newss
                           where n.AddTime >= start
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            //0001
            else if (title == "" && cont == "" && start == null && end != null)
            {
                var news = from n in db.Newss
                           where n.AddTime <= end
                           orderby n.AddTime descending
                           select n;
                return View(news);
            }
            else
            {
                return RedirectToAction("Index");
            }

        }

        public ActionResult Details(int id) 
        {
            var news = db.Newss.Find(id);


            if (news == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                news.ClickNum++;
                UpdateModel(news);
                db.SaveChanges();
            }
            var n1 = from n in db.Newss
                       where n.NewsId == id
                       select n;
            ViewData["newsDetails"] = n1;
            return View();
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult NewsCreate() 
        {
            string contents = HttpUtility.HtmlDecode(Request.Form["Contents"]);
            News news = new News
            {
                NewsTitle = Request.Form["NewsTitle"],
                Contents = contents,
                AddTime = DateTime.Now,
                Editor = HttpContext.User.Identity.Name,
                ClickNum = 1,
                NewsType1 = Convert.ToInt32(Request.Form["newstype1"]),
                NewsType2 = Convert.ToInt32(Request.Form["newstype2"])
            };
            if (ModelState.IsValid)
            {
                db.Newss.Add(news);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else 
            {
                return RedirectToAction("Create");
            }
        }


        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit(int id)
        {
            News news = db.Newss.Find(id);
            if (news == null)
            {
                return RedirectToAction("Index");
            }
            return View(news);
        }

        [Authorize(Roles = "Admin,Editer")]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(News model)
        {
            try
            {
                var news = db.Newss.Find(model.NewsId);
                UpdateModel(news);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = model.NewsId });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
            }
            return View(model);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id)
        {
            News news = db.Newss.Find(id);
            if (news == null)
                return RedirectToAction("Index");
            return View(news);
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public RedirectToRouteResult Delete(int id, FormCollection collection)
        {
            var news = db.Newss.Find(id);
            db.Newss.Remove(news);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        

    }
}
